<template>
  <view class="content">
    <view class="pos_content">
      <show-pos :posInfo="posInfo"></show-pos>
    </view>
    <view class="pos_head">
      <button type="primary" class="pos_btn" @click="getPos">
        获取当前位置
      </button>
    </view>
  </view>
</template>

<script>
// import showPos from "@components/position/showPos.vue";
import showPos from "../../components/position/showPos.vue";
// 引入请求模块
// import { postRequest } from "../../api/api";
// // 引入url
// import { postPosHistory } from "../../api/request";
// 引入请求模块
import { getRequest } from "@/api/api.js";
// 引入url
import { getPos } from "@/api/request.js";

export default {
  name: "position",
  components: {
    showPos,
  },
  created() {
    this.getPosInfo();
  },
  data() {
    return {
      // // 位置信息
      posInfo: {},
      is_post: false,
    };
  },
  methods: {
    // 获取地图信息
    async getPos() {
      const info = await this.choosePos();
      this.posInfo = info;
    },
    // 展示地图，选择地址
    async choosePos() {
      var that = this;
      return await new Promise((resolve, reject) => {
        uni.chooseLocation({
          success: function (res) {
            // 保存位置记录
            if (!that.is_post) {
              let options = {};
              options.name = res.name;
              options.address = res.address;
              options.latitude = res.latitude;
              options.longitude = res.longitude;
              postRequest(postPosHistory, options);
              that.is_post = true;
            }
            console.log(res);
            console.log("位置名称：" + res.name);
            console.log("详细地址：" + res.address);
            console.log("纬度：" + res.latitude);
            console.log("经度：" + res.longitude);
            uni.setStorage({
              key: "position",
              data: res,
              success: function () {
                console.log("setPosition success");
              },
            });
            resolve(res);
          },
          fail: function (err) {
            reject(err);
          },
        });
      });
    },
    async getPosInfo() {
      // console.log("---getPosInfo-");
      // this.posInfo = uni.getStorageSync("position");
      // console.log(this.posInfo);
      const result = await getRequest(getPos);
      console.log(result);
      if (result[1].data.status === 0) {
        this.getPos = result[1].data.data;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  .pos_head {
    width: 100%;
    height: 50vh;
    position: relative;
    .pos_btn {
      width: 60%;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      top: 20%;
      text-align: center;
    }
  }
}
</style>